package com.breeze.components.task.xxl.config;

import cn.hutool.core.util.StrUtil;
import com.breeze.components.task.xxl.JobAutoRegister;
import com.breeze.components.task.xxl.NoOpScheduler;
import com.breeze.components.task.xxl.config.properties.XxlJobProperties;
import com.breeze.components.task.xxl.log.XxlJobLogAppender;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * xxlJob配置
 *
 * @author breeze
 */
@AutoConfiguration
@ConditionalOnProperty(prefix = "xxl.job", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(XxlJobProperties.class)
public class XxlJobConfig {

  @Bean
  public XxlJobSpringExecutor xxlJobExecutor(@Autowired XxlJobProperties xxlJobProperties) {
    XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
    xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdminAddresses());
    xxlJobSpringExecutor.setAppname(xxlJobProperties.getAppName());
    xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());
    xxlJobSpringExecutor.setLogPath(xxlJobProperties.getLogPath());
    xxlJobSpringExecutor.setLogRetentionDays(xxlJobProperties.getLogRetentionDays());
    if (StrUtil.isNotEmpty(xxlJobProperties.getIp())) {
      xxlJobSpringExecutor.setIp(xxlJobProperties.getIp());
    }
    if (StrUtil.isNotEmpty(xxlJobProperties.getAddressList())) {
      xxlJobSpringExecutor.setAddress(xxlJobProperties.getAddressList());
    }
    if (Objects.nonNull(xxlJobProperties.getPort())) {
      xxlJobSpringExecutor.setPort(xxlJobProperties.getPort());
    }
    return xxlJobSpringExecutor;
  }

  @Bean
  public JobAutoRegister scheduledJobAutoRegister() {
    // 如果使用xxlJob,禁用掉spring自带的定时任务
    return new JobAutoRegister(new NoOpScheduler());
  }

  @Bean
  public XxlJobLogAppender xxlJobLogAppender() {
    return new XxlJobLogAppender();
  }
}
